home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 3_12.lha / 3_12 / 3_12.c next >
C/C++ Source or Header  |  1993-08-08  |  2KB  |  79 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. / Read a token into the buffer.
  6. / Read a line at a time.
  7. include <stdlib.h>
  8. include <error.h>
  9.  
  10. oken_value get_token()
  11.  
  12.    static char linebuf[512] = "";
  13.    static int lineindex = 0;
  14.  
  15.    // if line is empty, fill it
  16.    if (linebuf[lineindex] == '\0')
  17. {
  18. if (!cin.get(linebuf, sizeof linebuf - 1))
  19.     return (curr_tok = END);
  20.  
  21. // discard newline from input
  22. char c;
  23. cin.get(c);
  24.  
  25. // install newline within line
  26. int end = strlen(linebuf);
  27. linebuf[end++] = '\n';
  28. linebuf[end] = '\0';
  29. lineindex = 0;
  30. }
  31.  
  32.    // delete leading whitespace on the line
  33.    while (isspace(linebuf[lineindex]) &&
  34.    (linebuf[lineindex] != '\n'))
  35. lineindex++;
  36.  
  37.    // match a token
  38.    char ch;
  39.    switch (ch = linebuf[lineindex++])
  40. {
  41. case ';': case '\n':
  42.     return (curr_tok = PRINT);
  43.  
  44. case '*': case '+': case '(':
  45. case '/': case '-': case ')':
  46. case ':':
  47.     return (curr_tok = ch);
  48.  
  49. // match a number
  50. case '0': case '1': case '2': case '3':
  51. case '4': case '5': case '6': case '7':
  52. case '8': case '9': case '.':
  53.     int saveindex = lineindex - 1;
  54.     while (isdigit(ch = linebuf[lineindex]) ||
  55.        (ch == '.'))
  56.     lineindex++;
  57.  
  58.     linebuf[lineindex] = '\0';
  59.     number_value = atof(&linebuf[saveindex]);
  60.     linebuf[lineindex] = ch;
  61.     return (curr_tok = NUMBER);
  62.  
  63. default:
  64.     if (isalpha(ch))
  65.     {
  66.     char *p = name_string;
  67.     for (*p++ = ch;
  68.          isalnum(ch = linebuf[lineindex]);
  69.          *p++ = ch, lineindex++)
  70.         ;
  71.     *p = '\0';
  72.     return (curr_tok = NAME);
  73.     }
  74.  
  75.     error("unknown token received");
  76.     return (curr_tok = PRINT);
  77. }
  78.  
  79.